# -*- encoding: utf-8 -*-
from src.ApiTest.Core.connect_redis import Redis
from src.ApiTest.Core.connect_db import SQL
from Common.log import MyLog
import time


class OperationalDB:
    """
    操作数据库
    """
    def __init__(self):
        self.log = MyLog

    @staticmethod
    def connect_db(db_info):
        """
        连接数据库
        :param db_info:
        :return:
        """
        try:
            db_type = db_info['databaseType']
        except Exception as e:
            raise KeyError('请选择数据库类型')
        if db_type == 'redis':
            connect = Redis().connect_database(db_info)
            return connect
        else:
            connect = SQL().connect_database(db_info)
            return connect

    def sql_return_result(self, db_info, sql):
        """
        运行sql语句
        :param db_info: 数据库基础信息
        :param sql: sql语句
        :return data
        """

        # 连接数据库
        db = self.connect_db(db_info)

        # 使用cursor()方法获取操作游标
        cursor = db.cursor()
        try:
            # 使用execute方法执行SQL语句
            cursor.execute(sql)
            # 获取表的所有字段名称
            coloumns = [row[0] for row in cursor.description]
            result = [[str(item) for item in row] for row in cursor.fetchall()]
            datas = [dict(zip(coloumns, row)) for row in result]
            self.log.info(sql)
        except Exception as e:
            # 发生错误时回滚
            db.rollback()
            self.log.error('事务处理失败！error:' + str(e) + '\n错误sql：' + str(sql))
            return False
        else:
            db.commit()
            self.log.info('事务处理成功  ^_^')
            return datas

    def sql_no_return(self, db_info, sql):
        """
        运行sql语句
        :param db_info: 数据库基础信息
        :param sql: sql语句
        :return data
        """

        # 连接数据库
        db = self.connect_db(db_info)

        # 使用cursor()方法获取操作游标
        cursor = db.cursor()
        try:
            # 使用execute方法执行SQL语句
            cursor.execute(sql)
            db.commit()
            return 'success'
        except Exception as e:
            # 发生错误时回滚
            db.rollback()
            self.log.error('事务处理失败！error:' + str(e) + '\n错误sql：' + str(sql))
            return False

    def get_redis_value(self, db_info, key):
        """
        封装根据key获取redis中value的方法
        :param db_info:
        :param key: key，必填
        """
        value = self.connect_db(db_info).get(key)
        return value

    def delete_redis_key(self, db_info, key):
        """
        删除redis基础方法
        :param db_info:
        :param key:
        :return:
        """
        try:
            self.connect_db(db_info).delete(key)
            MyLog().info('-------- 删除成功 -----------')
            return 'success'
        except Exception as e:
            raise e

    def insert_redis_key(self, db_info, key, value):
        """
        封装插入redis键值的方法
        """
        try:
            self.connect_db(db_info).set(key, value)
            MyLog().info('-------- 插入成功 -----------')
            return 'success'
        except Exception as e:
            raise e